package com.hc.framework.utils;

import java.util.Random;

/**
 * Created by Admin on 2017/1/9.
 */
public class StringUtil {

    /**
     *任意一个字符串 比如"abc我爱中国" 大于12个字节的 要截取掉,用 ... 来结尾, 最终结果不能大于12个字节  注 中文占2个字节
     */
    public static String subStringCN(final String str, final int maxLength) {
        if (str == null) {
            return str;
        }
        String suffix = "...";
        int suffixLen = suffix.length();

        final StringBuffer sbuffer = new StringBuffer();
        final char[] chr = str.trim().toCharArray();
        int len = 0;
        for (int i = 0; i < chr.length; i++) {

            if (chr[i] >= 0xa1) {
                len += 2;
            } else {
                len++;
            }
        }

        if(len<=maxLength){
            return str;
        }

        len = 0;
        for (int i = 0; i < chr.length; i++) {

            if (chr[i] >= 0xa1) {
                len += 2;
                if (len + suffixLen > maxLength) {
                    break;
                }else {
                    sbuffer.append(chr[i]);
                }
            } else {
                len++;
                if (len + suffixLen > maxLength) {
                    break;
                }else {
                    sbuffer.append(chr[i]);
                }
            }
        }
        sbuffer.append(suffix);
        return sbuffer.toString();
    }


    public static String subStringdel(String str) {
        str=str.replace("第","");
        str=str.replace("题【单选】：","");
        str=str.replace("题【判断】：","");
        str=str.replace("题【多选】：","");
        return str;
    }

    public static String gettype(String str) {
        String nstr="";
        if(str.indexOf("判断")!=-1){
            nstr="判断";
        }
        if(str.indexOf("单选")!=-1){
            nstr="单选";
        }
        if(str.indexOf("多选")!=-1){
            nstr="多选";
        }
        return nstr;
    }

    //生成随机文件名
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return "2017_"+sb.toString();
    }

}
